package com.qf.java2105.huangchuang.hotel.filters;


import com.qf.java2105.huangchuang.hotel.constant.ResponseMessageConstant;
import com.qf.java2105.huangchuang.hotel.pojo.User;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author hcvg
 * @version v1.0
 * @date 2021/09/16
 **/
@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        User user = (User) request.getSession().getAttribute("userTemp");
        String uri = request.getRequestURI();
        if (uri.endsWith(".html") || uri.endsWith("/login.jsp") || uri.endsWith(".css") || uri.endsWith(".js") || uri.endsWith("/user") || uri.endsWith("getValidateCode")){
            filterChain.doFilter(request, response);
            return;
        }
        if (null == user){
            response.sendRedirect(request.getContextPath() + "/user?method=login");
            return;
        }

        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
